#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
环境变量配置检查脚本

对照config.py和.env文件，确保所有必需的环境变量都已正确配置
"""

import os
import sys
from pathlib import Path
from typing import Dict, List, Tuple

# 添加项目根目录到Python路径  
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

def load_env_file(env_path):
    """加载.env文件"""
    env_vars = {}
    
    if not env_path.exists():
        return env_vars
    
    with open(env_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#') and '=' in line:
                key, value = line.split('=', 1)
                env_vars[key.strip()] = value.strip()
    
    return env_vars

def extract_config_fields():
    """从config.py提取所有环境变量字段"""
    config_fields = []
    
    try:
        from src.core.config import Settings
        
        # 获取Settings类的所有字段
        for field_name, field_info in Settings.__fields__.items():
            if hasattr(field_info, 'field_info') and hasattr(field_info.field_info, 'extra'):
                env_name = field_info.field_info.extra.get('env')
                if env_name:
                    config_fields.append(env_name)
            elif hasattr(field_info, 'alias'):
                config_fields.append(field_info.alias or field_name)
            else:
                # 对于直接使用Field(..., env="ENV_NAME")的情况
                config_fields.append(field_name)
    
    except Exception as e:
        print(f"❌ 无法导入配置类: {e}")
        # 手动列出已知的环境变量
        config_fields = [
            'DEBUG', 'SECRET_KEY', 'HOST', 'PORT',
            'DATABASE_URL', 'DATABASE_POOL_SIZE', 'DATABASE_MAX_OVERFLOW',
            'ACCESS_TOKEN_EXPIRE_MINUTES', 'REFRESH_TOKEN_EXPIRE_DAYS',
            'REDIS_URL', 'REDIS_PASSWORD', 'REDIS_EXPIRE_TIME',
            'CAPTCHA_EXPIRE_SECONDS', 'LOGIN_FAIL_THRESHOLD', 'LOGIN_FAIL_LOCK_SECONDS',
            'BACKEND_CORS_ORIGINS', 'ALLOWED_HOSTS',
            'MAX_FILE_SIZE', 'UPLOAD_DIR',
            'LOG_LEVEL', 'LOG_FILE',
            'CACHE_TTL', 'ENABLE_METRICS',
            'TOURISM_SEASON_HIGH', 'TOURISM_SEASON_LOW',
            'DEFAULT_TOUR_INSURANCE', 'MIN_GROUP_SIZE', 'MAX_GROUP_SIZE',
            'BOOKING_ADVANCE_DAYS', 'NOTIFICATION_EMAIL_ENABLED',
            'NOTIFICATION_SMS_ENABLED', 'EMERGENCY_CONTACT_PHONE'
        ]
    
    return config_fields

def check_required_vs_optional():
    """区分必需和可选的环境变量"""
    required_vars = [
        'SECRET_KEY',
        'DATABASE_URL',
    ]
    
    optional_vars = [
        'DEBUG', 'HOST', 'PORT',
        'DATABASE_POOL_SIZE', 'DATABASE_MAX_OVERFLOW', 
        'ACCESS_TOKEN_EXPIRE_MINUTES', 'REFRESH_TOKEN_EXPIRE_DAYS',
        'REDIS_URL', 'REDIS_PASSWORD', 'REDIS_EXPIRE_TIME',
        'CAPTCHA_EXPIRE_SECONDS', 'LOGIN_FAIL_THRESHOLD', 'LOGIN_FAIL_LOCK_SECONDS',
        'BACKEND_CORS_ORIGINS', 'ALLOWED_HOSTS',
        'MAX_FILE_SIZE', 'UPLOAD_DIR', 'ALLOWED_FILE_TYPES',
        'LOG_LEVEL', 'LOG_FILE',
        'CACHE_TTL', 'ENABLE_METRICS',
        'TOURISM_SEASON_HIGH', 'TOURISM_SEASON_LOW',
        'DEFAULT_TOUR_INSURANCE', 'MIN_GROUP_SIZE', 'MAX_GROUP_SIZE',
        'BOOKING_ADVANCE_DAYS', 'NOTIFICATION_EMAIL_ENABLED',
        'NOTIFICATION_SMS_ENABLED', 'EMERGENCY_CONTACT_PHONE',
        'SMTP_SERVER', 'SMTP_PORT', 'SMTP_USERNAME', 'SMTP_PASSWORD', 'SMTP_USE_TLS',
        'SMS_PROVIDER', 'SMS_ACCESS_KEY', 'SMS_SECRET_KEY'
    ]
    
    return required_vars, optional_vars

def main():
    """主检查函数"""
    print("🔍 环境变量配置检查")
    print("=" * 50)
    
    # 文件路径
    env_file = project_root / ".env"
    env_example_file = project_root / ".env.example"
    
    # 加载文件
    env_vars = load_env_file(env_file)
    env_example_vars = load_env_file(env_example_file)
    
    # 获取配置字段
    config_fields = extract_config_fields()
    required_vars, optional_vars = check_required_vs_optional()
    
    print(f"📁 .env文件: {'存在' if env_file.exists() else '❌ 不存在'}")
    print(f"📁 .env.example文件: {'存在' if env_example_file.exists() else '❌ 不存在'}")
    print(f"📊 配置中定义的变量: {len(config_fields)}个")
    print(f"📊 .env中定义的变量: {len(env_vars)}个")
    print(f"📊 .env.example中定义的变量: {len(env_example_vars)}个")
    
    print("\n" + "=" * 50)
    
    # 检查必需变量
    print("✅ 必需环境变量检查:")
    missing_required = []
    for var in required_vars:
        if var in env_vars and env_vars[var]:
            print(f"  ✅ {var}: 已配置")
        else:
            print(f"  ❌ {var}: 缺失或为空")
            missing_required.append(var)
    
    # 检查验证码相关变量
    print("\n🔐 验证码相关变量检查:")
    captcha_vars = ['REDIS_URL', 'CAPTCHA_EXPIRE_SECONDS', 'LOGIN_FAIL_THRESHOLD', 'LOGIN_FAIL_LOCK_SECONDS']
    for var in captcha_vars:
        if var in env_vars:
            print(f"  ✅ {var}: {env_vars[var]}")
        else:
            print(f"  ❌ {var}: 缺失")
    
    # 检查.env与config.py的同步
    print("\n🔄 配置同步检查:")
    in_config_not_in_env = []
    for field in config_fields:
        if field not in env_vars and field in required_vars + optional_vars:
            in_config_not_in_env.append(field)
    
    if in_config_not_in_env:
        print("  ⚠️  config.py中定义但.env中缺失的变量:")
        for var in in_config_not_in_env:
            print(f"    - {var}")
    else:
        print("  ✅ 配置文件与.env文件同步良好")
    
    # 检查.env与.env.example的同步
    print("\n📋 示例文件同步检查:")
    in_env_not_in_example = []
    for var in env_vars:
        if var not in env_example_vars and not var.startswith('#'):
            in_env_not_in_example.append(var)
    
    if in_env_not_in_example:
        print("  ⚠️  .env中有但.env.example中缺失的变量:")
        for var in in_env_not_in_example:
            print(f"    - {var}")
    else:
        print("  ✅ .env与.env.example文件同步良好")
    
    # 总结
    print("\n" + "=" * 50)
    print("📋 检查总结:")
    
    if missing_required:
        print(f"❌ 缺失 {len(missing_required)} 个必需环境变量")
        print("请在.env文件中添加以下变量:")
        for var in missing_required:
            print(f"  {var}=<your-value>")
    else:
        print("✅ 所有必需环境变量都已配置")
    
    if in_config_not_in_env:
        print(f"⚠️  建议添加 {len(in_config_not_in_env)} 个可选环境变量")
    
    print("\n🚀 快速启动检查:")
    redis_configured = 'REDIS_URL' in env_vars and env_vars['REDIS_URL']
    secret_configured = 'SECRET_KEY' in env_vars and len(env_vars.get('SECRET_KEY', '')) >= 32
    db_configured = 'DATABASE_URL' in env_vars and env_vars['DATABASE_URL']
    
    print(f"  Redis配置: {'✅' if redis_configured else '❌'}")
    print(f"  密钥配置: {'✅' if secret_configured else '❌'}")  
    print(f"  数据库配置: {'✅' if db_configured else '❌'}")
    
    if redis_configured and secret_configured and db_configured:
        print("\n🎉 配置检查通过！可以启动系统进行验证码测试")
        print("运行命令:")
        print("  python main_web.py        # 启动后端")
        print("  python test_captcha.py    # 测试验证码功能")
    else:
        print("\n⚠️  配置不完整，请修复上述问题后再启动系统")

if __name__ == "__main__":
    main()